package us.codecraft.webmagic.proxyprovider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.dao.ProxyDao;
import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.ProxyProvider;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author : xuaoping
 * @Date: 2021/8/17
 */
@Service
@Slf4j
public class DefaultProxyProvider implements ProxyProvider {

    @Autowired
    private ProxyDao proxyDao;

    private List<Proxy> proxies = new ArrayList<>();

    private final AtomicInteger pointer = new AtomicInteger(0);

    @Override
    public synchronized void returnProxy(Proxy proxy, Page page, Task task) {
        if (!page.isDownloadSuccess()) {
            log.info("remove proxy:{}", proxy);
            proxyDao.updateUsable(((us.codecraft.webmagic.proxyprovider.Proxy) proxy).getId(), 0);
            proxies.remove(proxy);
        }
    }

    @Override
    public synchronized Proxy getProxy(Task task) {
        if (proxies.isEmpty()) {
            proxies.addAll(proxyDao.getList());
        }
        if (!proxies.isEmpty()) {
            return proxies.get(incrForLoop());
        } else {
            log.info("proxy not enough....");
            return null;
        }
    }

    private int incrForLoop() {
        int p = pointer.incrementAndGet();
        int size = proxies.size();
        if (p < size) {
            return p;
        }
        while (!pointer.compareAndSet(p, p % size)) {
            p = pointer.get();
        }
        return p % size;
    }
}
